/**
 * 文件处理相关的组合式API
 * 负责附件类型检测、图标显示和下载处理
 */
import { Document, Picture, VideoPlay, Files } from '@element-plus/icons-vue';

interface AttachmentFile {
  url: string;
  name?: string;
  type?: string;
  size?: number;
}

export function useFileUtils() {
  // 文件类型检测
  function isDocType(file: { type?: string; url: string }): boolean {
    const docTypes = ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'];
    const fileType = file.type || file.url.split('.').pop()?.toLowerCase() || '';
    return docTypes.includes(fileType);
  }

  function isImageType(file: { type?: string; url: string }): boolean {
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    const fileType = file.type || file.url.split('.').pop()?.toLowerCase() || '';
    return imageTypes.includes(fileType);
  }

  function isVideoType(file: { type?: string; url: string }): boolean {
    const videoTypes = ['mp4', 'avi', 'mov', 'wmv', 'flv'];
    const fileType = file.type || file.url.split('.').pop()?.toLowerCase() || '';
    return videoTypes.includes(fileType);
  }

  // 获取文件图标组件
  function getFileIcon(file: { type?: string; url: string }) {
    if (isDocType(file)) return Document;
    if (isImageType(file)) return Picture;
    if (isVideoType(file)) return VideoPlay;
    return Files;
  }

  // 获取文件图标类名
  function getFileIconClass(file: { type?: string; url: string }): string {
    if (isDocType(file)) return 'file-icon doc';
    if (isImageType(file)) return 'file-icon image';
    if (isVideoType(file)) return 'file-icon video';
    return 'file-icon other';
  }

  // 从URL中获取文件名
  function getFileName(url: string): string {
    if (!url) return '未命名文件';
    return url.split('/').pop() || '未命名文件';
  }

  // 格式化文件大小
  function formatFileSize(size?: number): string {
    if (!size) return '未知大小';

    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let fileSize = size;
    let unitIndex = 0;

    while (fileSize >= 1024 && unitIndex < units.length - 1) {
      fileSize /= 1024;
      unitIndex++;
    }

    return `${fileSize.toFixed(2)} ${units[unitIndex]}`;
  }

  // 下载附件
  function downloadAttachment(attachment: AttachmentFile): void {
    if (!attachment.url) return;

    // 显示下载状态
    const notification = {
      message: `正在下载: ${attachment.name || getFileName(attachment.url)}`,
      type: 'info',
      duration: 0
    };

    // 使用Fetch API下载，可以显示进度
    fetch(attachment.url)
      .then((response) => {
        if (!response.ok) {
          throw new Error(`下载失败: ${response.status} ${response.statusText}`);
        }
        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = attachment.name || getFileName(attachment.url);
        document.body.appendChild(link);
        link.click();

        // 清理
        setTimeout(() => {
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }, 100);
      })
      .catch((error) => {
        console.error('下载文件失败:', error);
        // 使用备用方法下载
        const link = document.createElement('a');
        link.href = attachment.url;
        link.target = '_blank';
        link.download = attachment.name || getFileName(attachment.url);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
  }

  return {
    isDocType,
    isImageType,
    isVideoType,
    getFileIcon,
    getFileIconClass,
    getFileName,
    formatFileSize,
    downloadAttachment
  };
} 